import { error, instantiate, _decorator } from 'cc';
import { VM } from './ViewModel';
import VMBase from './VMBase';

const { ccclass, property, menu, help } = _decorator;
@ccclass
@menu('ModelViewer/VM-StateChildsTwo (VM状态控制)')
export default class VMStateChildsTwo extends VMBase {
    @property
    watchPath: string = "";

    @property([Node])
    copyNodeArr: Node[] = [];

    @property(Node)
    parentGroup: Node = null;




    onLoad() {
        for (const copy of this.copyNodeArr) {
            (copy as any).active = false;
        }
        super.onLoad();
    }

    //当值初始化时
    protected onValueInit() {
        let value = VM.getValue(this.watchPath);
        this.node.removeAllChildren();
        let i = 0;
        for (const vo of value) {
            this.addOne(vo, i);
            i++;
        }
    }

    //当值被改变时
    protected onValueChanged(newVar: any[], oldVar: any[], pathArr: any[]) {
        let newMap = {};
        let oldMap = {};
        for (const vo of newVar) {
            newMap[vo.key] = vo;
        }
        for (const vo of oldVar) {
            oldMap[vo.key] = vo;
        }

        for (const key in newMap) {
            if (!oldMap[key]) {
                this.addOne(newMap[key], newVar.indexOf(newMap[key]));
            }
        }

        for (const key in oldMap) {
            if (!newMap[key]) {
                var data = oldMap[key];
                var node = (this.parentGroup as any).getChildByName(data.key);
                if (node) {
                    node.destroy();
                }
                else {
                   error("VMStateChilds不存在" + data.key);
                }
            }
        }
    }
    private addOne(vo: any, index: number) {
        let node: any;
        if (index < 3)
            node = instantiate(this.copyNodeArr[0]);
        else
            node = instantiate(this.copyNodeArr[1]);
        node.name = vo.key;
        node.parent = this.parentGroup;
        node.active = true;
    }
}